package controllers

import (
	"encoding/json"
	"github.com/astaxie/beego"
	"path/filepath"
	"shop/models"
	"strconv"
	"strings"
	"time"
)

type ShopController struct {
	beego.Controller
}

type JsonRes struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

func (c *ShopController) Add() {
	name := c.GetString("name")
	img := c.GetString("img")
	cate := c.GetString("cate")
	uptime := c.GetString("uptime")
	tel := c.GetString("tel")
	address := c.GetString("address")
	detail := c.GetString("detail")
	shop := models.Shop{
		Name:    name,
		Img:     img,
		Cate:    cate,
		Uptime:  uptime,
		Tel:     tel,
		Address: address,
		Detail:  detail,
	}
	err := models.DB.Create(&shop).Error
	if err != nil {
		c.Data["json"] = JsonRes{
			Code: 500,
			Msg:  "添加失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		c.Data["json"] = JsonRes{
			Code: 200,
			Msg:  "添加成功",
			Data: nil,
		}
		c.ServeJSON()
	}
}
func (c *ShopController) Upload() {
	file, header, err := c.GetFile("img")
	if err != nil {
		c.Data["json"] = JsonRes{
			Code: 500,
			Msg:  "请选择文件",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	defer file.Close()

	if header.Size > 5*1024*1024 {
		c.Data["json"] = JsonRes{
			Code: 500,
			Msg:  "文件过大,不能超过5MB",
			Data: nil,
		}
		c.ServeJSON()
	}

	ext := strings.ToLower(filepath.Ext(header.Filename))
	allowExt := map[string]bool{
		".jpeg": true,
		".png":  true,
	}
	if !allowExt[ext] {
		c.Data["json"] = JsonRes{
			Code: 200,
			Msg:  "文件格式不对,只能是JPEG,PNG格式",
			Data: nil,
		}
		c.ServeJSON()
	}
	path := "static/img/" + header.Filename
	err = c.SaveToFile("img", path)
	if err != nil {
		c.Data["json"] = JsonRes{
			Code: 500,
			Msg:  "上传失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		imgUrl := "http://127.0.0.1:8080/" + path
		c.Data["json"] = JsonRes{
			Code: 200,
			Msg:  "上传成功",
			Data: imgUrl,
		}
		c.ServeJSON()
	}
}
func (c *ShopController) List() {
	pageData := make(map[string]interface{})
	query := models.DB.Model(&models.Shop{})
	page, _ := c.GetInt("p", 1)
	size, _ := c.GetInt("s", 10)
	key := "page-" + strconv.Itoa(page)
	val, err := models.Rdb.Get(key).Result()
	if err != nil {
		var count int64
		query.Count(&count)

		var shop []models.Shop
		offset := (page - 1) * size
		err = query.Offset(offset).Limit(size).Find(&shop).Error
		if err != nil {
			c.Data["json"] = JsonRes{
				Code: 0,
				Msg:  "查询失败",
				Data: nil,
			}
			c.ServeJSON()
			return
		}
		pageData["count"] = count
		pageData["house"] = shop

		jsonByte, _ := json.Marshal(&pageData)
		value := string(jsonByte)
		models.Rdb.Set(key, value, time.Minute*3)
		c.Data["json"] = JsonRes{
			Code: 200,
			Msg:  "查询成功-mysql",
			Data: pageData,
		}
		c.ServeJSON()
		return
	} else {
		json.Unmarshal([]byte(val), &pageData)
		c.Data["json"] = JsonRes{
			Code: 200,
			Msg:  "查询成功-redis",
			Data: pageData,
		}
		c.ServeJSON()
	}
}
func (c *ShopController) Info() {
	id, _ := c.GetInt("id")
	key := "shop-" + strconv.Itoa(id)
	val, err := models.Rdb.Get(key).Result()
	RankKey := "shop-rank"
	var shop models.Shop
	if err != nil {
		err = models.DB.Where("id=?", id).First(&shop).Error
		if err != nil {
			c.Data["json"] = JsonRes{
				Code: 0,
				Msg:  "详情展示失败",
				Data: nil,
			}
			c.ServeJSON()
			return
		} else {
			models.Rdb.ZIncrBy(RankKey, 1, shop.Name)
			jsonByte, _ := json.Marshal(&shop)
			value := string(jsonByte)
			models.Rdb.Set(key, value, time.Minute*3)
			c.Data["json"] = JsonRes{
				Code: 200,
				Msg:  "展示成功-mysql",
				Data: shop,
			}
			c.ServeJSON()
		}
	} else {
		json.Unmarshal([]byte(val), &shop)
		models.Rdb.ZIncrBy(RankKey, 1, shop.Name)
		c.Data["json"] = JsonRes{
			Code: 200,
			Msg:  "展示成功-redis",
			Data: shop,
		}
		c.ServeJSON()
	}
}
func (c *ShopController) Rank() {
	key := "shop-rank"
	nums := models.Rdb.ZCard(key).Val()
	ranks, err := models.Rdb.ZRevRangeWithScores(key, 0, nums-1).Result()
	if err != nil {
		c.Data["json"] = JsonRes{
			Code: 500,
			Msg:  "展示失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = JsonRes{
			Code: 200,
			Msg:  "展示成功",
			Data: ranks,
		}
		c.ServeJSON()
	}
}
func (c *ShopController) Delete() {
	id, _ := c.GetInt("id")
	err := models.DB.Where("id=?", id).Delete(&models.Shop{}).Error
	if err != nil {
		c.Data["json"] = JsonRes{
			Code: 500,
			Msg:  "删除失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		c.Data["json"] = JsonRes{
			Code: 200,
			Msg:  "删除成功",
			Data: nil,
		}
		c.ServeJSON()
	}
}
func (c *ShopController) Update() {
	id, _ := c.GetInt("id")
	cate := c.GetString("cate")
	shop := models.Shop{
		Cate: cate,
	}
	err := models.DB.Where("id=?", id).Updates(&shop).Error
	if err != nil {
		c.Data["json"] = JsonRes{
			Code: 500,
			Msg:  "修改失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = JsonRes{
			Code: 200,
			Msg:  "修改成功",
			Data: nil,
		}
		c.ServeJSON()
	}
}
